<template>
  <div class="update-name">
    <van-nav-bar
    title="编辑修改昵称"
    left-text="取消"
    right-text="确定"
    @click-left="$emit('close')"
    @click-right="onclick"
    />
    <div style="padding: 10px">
      <van-field
      v-model="localName"
      rows="2"
      autosize
      type="textarea"
      maxlength="7"
      placeholder="请输入昵称"
      show-word-limit
    />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  data () {
    return {
      localName: ''
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  created () {
    this.localName = this.value
  },
  methods: {
    async onclick () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })
      try {
        if (!this.localName.trim) {
          this.$toast('不能为空')
          return
        } else {
          await updateUserProfile({
            name: this.localName
          })
          // 触发 v-model 的 input事件
          this.$emit('input', this.localName)
          // 成功后关闭弹出层
          this.$emit('close')
          this.$toast.success('更新成功')
        }
      } catch (err) {
        console.dir(err)
        if (err.response && err.response.status === 409) {
          return this.$toast('用户名已存在')
        }
        this.$toast('修改失败,请重试')
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
